package services;

import java.util.ArrayList;
import java.util.List;

import models.Resource;
import models.ResourceHierarchy;
import models.ResourceHierarchyPK;
import models.ResourceType;

public abstract class ResourceService {
	
	protected Resource getResource(long resourceId) {
		return Resource.find.byId(resourceId);
	}
	
	protected List<Resource> getParentResources(long resourceId, ResourceType resourceType) {
		List<Resource> resources = new ArrayList<Resource>();
		if (resourceId > 0) {
			List<ResourceHierarchy> parentResources = ResourceHierarchy.find.where().eq("child_id", resourceId).findList();
			Resource parentResource;
			for (ResourceHierarchy parent : parentResources) {
				parentResource = Resource.find.byId(parent.getHierarchyPK().getParentId());
				if (parentResource.getType() == resourceType) {
					resources.add(parentResource);
				}
			}
		}
		return resources;
	}
	
	protected List<Resource> getChildResources(long parentResourceId, ResourceType resourceType) {
		List<Resource> resources = new ArrayList<Resource>();
		if (parentResourceId > 0) {
			List<ResourceHierarchy> childResources = ResourceHierarchy.find.where().eq("parent_id", parentResourceId).findList();
			Resource childResource;
			for (ResourceHierarchy child : childResources) {
				childResource = Resource.find.byId(child.getHierarchyPK().getChildId());
				if (childResource.getType() == resourceType) {
					resources.add(childResource);
				}
			}
		}
		return resources;
	}
	
	protected void createHierarchy(long parentResourceId, long childResourceId) {
		ResourceHierarchyPK pk = new ResourceHierarchyPK();
		pk.setParentId(parentResourceId);
		pk.setChildId(childResourceId);
		ResourceHierarchy rh = new ResourceHierarchy(pk);
		rh.save();
	}
	
	protected void removeHierarchy(long parentResourceid, long childResourceId) {
		ResourceHierarchyPK pk = new ResourceHierarchyPK();
		pk.setParentId(parentResourceid);
		pk.setChildId(childResourceId);
		ResourceHierarchy h = ResourceHierarchy.find.byId(pk);
		if (h != null) {
			h.delete();
		}
	}
	
}
